<template>
  <a-card :bordered="false">
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="4">
        <a-form-item label="用戶uid">
          <a-input v-model="searchForm.uid" placeholder="請輸入用戶uid" allow-clear />
        </a-form-item>
      </a-col>
      <a-col :span="4">
        <a-form-item label="名稱">
          <a-input v-model="searchForm.nickname" placeholder="請輸入用戶名稱" allow-clear />
        </a-form-item>
      </a-col>
      <a-col :span="4">
        <a-form-item label="聯絡電話">
          <a-input v-model="searchForm.phone" placeholder="請輸入用戶聯絡電話" allow-clear />
        </a-form-item>
      </a-col>
      <a-col :span="4">
        <a-form-item label="信箱">
          <a-input v-model="searchForm.email" placeholder="請輸入用戶信箱" allow-clear />
        </a-form-item>
      </a-col>
      <a-col flex="300px">
        <a-button type="primary" style="margin-right: 8px" @click="init(1)"> 搜索 </a-button>
        <a-button style="margin-right: 8px" @click="resetSearch"> 重置 </a-button>
        <a-button type="primary" style="margin-right: 8px" @click="registrationExcel"> 導出 </a-button>
      </a-col>
    </a-row>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="8">
        <a-form-item field="title" label="日期篩選">
          <a-range-picker
            v-model="dateRange"
            showTime
            :time-picker-props="{
              defaultValue: ['00:00:00', '00:00:00'],
            }"
            @change="onChange"
            style="width: 100%" />
        </a-form-item>
      </a-col>
      <a-col :span="4">
        <a-form-item field="status" label="狀態">
          <a-select v-model="searchForm.status" @change="init(1)" placeholder="請選擇狀態" alow-clear>
            <a-option label="全部" :value="-1" />
            <a-option label="未審核" :value="0" />
            <a-option label="已通過" :value="1" />
            <a-option label="已拒絕" :value="2" />
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="4"> </a-col>
      <a-col flex="400px">
        <a-button type="primary" style="margin-right: 8px" @click="batchPass"> 批量通過 </a-button>
        <a-button @click="batchReject"> 批量拒絕 </a-button>
        <a-button type="primary" style="margin-right: 8px" @click="openUploadExcel"> 批量更新 </a-button>
      </a-col>
    </a-row>
    <div ref="crudContentRef">
      <a-table
        :loading="loading"
        :scroll="{ x: '100%', y: '100%' }"
        :columns="columns"
        :pagination="false"
        :row-selection="rowSelection"
        v-model:selectedKeys="selectedKeys"
        row-key="uid"
        :data="data">
        <template #signUpTime="{ record }">
          {{ dateFormat(record.signUpTime) }}
        </template>
        <template #optional="{ record }">
          <a-link v-if="!record.status" status="success" v-auth="[1, 2]" @click="batchPass(record)"> 通過 </a-link>
          <a-link v-if="!record.status" status="danger" v-auth="[1, 2]" @click="batchReject(record)"> 拒絕 </a-link>
          <span v-else>--</span>
        </template>
      </a-table>
    </div>
    <div class="mt-2 text-right" v-if="data.length > 0">
      <a-pagination
        :total="pageObj.total"
        show-total
        show-jumper
        show-page-size
        :page-size-options="[20, 30, 50, 100]"
        @page-size-change="pageSizeChangeHandler"
        @change="pageChangeHandler"
        v-model:current="pageObj.page"
        :page-size="pageObj.pageSize"
        style="display: inline-flex" />
    </div>
    <a-modal
      v-model:visible="uploadPopup"
      :ok-loading="btnLoading"
      @cancel="closeRematch"
      @before-ok="submitRematch"
      width="40%">
      <a-form-item label="上傳文件" field="imageUrl">
        <a-upload
          action="/"
          :auto-upload="false"
          :limit="1"
          ref="uploadRef"
          accept=".csv"
          :file-list="uploadFile"
          @change="onChangeUpload"
          :custom-request="customRequest"
          multiple>
          <template #upload-button>
            <a-space>
              <a-button>請選擇文件</a-button>
            </a-space>
          </template>
        </a-upload>
      </a-form-item>
      *CSV文件，需包含uid列（支持uid、user_id、用戶ID等列名）,傳入則直接通過審覈
    </a-modal>
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import registrationApi from '@/api/registration'
import tool from '@/utils/tool'

const pageObj = reactive({
  page: 1,
  pageSize: 20,
  total: 0,
})
const rowSelection = {
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: true,
}
const dateRange = ref([])
const selectedKeys = ref([])
const searchForm = reactive({
  status: 0,
  uid: '',
  nickname: '',
  phone: '',
  email: '',
  startTime: '',
  endTime: '',
})
const batchPass = async (row) => {
  if (selectedKeys.value.length === 0 && !row.uid) {
    Message.error('請選擇要操作的紀錄')
    return
  }
  loading.value = true
  try {
    await registrationApi.registrationBatchApproval({
      uidList: row.uid ? [row.uid] : selectedKeys.value,
      status: 1,
    })
    Message.success('操作成功')
    loading.value = false
    init()
  } catch (error) {
    loading.value = false
  }
}
const batchReject = async (row) => {
  if (selectedKeys.value.length === 0 && !row.uid) {
    Message.error('請選擇要操作的紀錄')
    return
  }
  loading.value = true
  try {
    await registrationApi.registrationBatchApproval({
      uidList: row.uid ? [row.uid] : selectedKeys.value,
      status: 2,
    })
    Message.success('操作成功')
    loading.value = false
    init()
  } catch (error) {
    loading.value = false
  }
}
const onChange = (dateString) => {
  if (dateString) {
    searchForm.startTime = dateString[0]
    searchForm.endTime = dateString[1]
  } else {
    searchForm.startTime = ''
    searchForm.endTime = ''
  }
  init(1)
}
const resetSearch = () => {
  searchForm.status = 0
  searchForm.uid = ''
  searchForm.nickname = ''
  searchForm.phone = ''
  searchForm.email = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
  pageObj.pageSize = 20
  dateRange.value = []
  init(1)
}

const columns = ref([
  {
    title: '暱稱',
    dataIndex: 'nickname',
  },
  {
    title: '聯絡電話',
    dataIndex: 'phone',
    width: 170,
  },
  {
    title: '信箱',
    dataIndex: 'email',
  },
  {
    title: '審核狀態',
    dataIndex: 'statusDesc',
    align: 'center',
    width: 100,
  },
  {
    title: '註冊時間',
    dataIndex: 'signUpTime',
    slotName: 'signUpTime',
    width: 170,
  },
  {
    title: '操作',
    slotName: 'optional',
    width: 170,
    align: 'center',
  },
])
const data = ref([])

const pageSizeChangeHandler = async (pageSize) => {
  pageObj.pageSize = pageSize
  init(1)
}
const pageChangeHandler = async (currentPage) => {
  init(currentPage)
}
const loading = ref(false)

const init = async (pageNum = 1) => {
  selectedKeys.value = []
  loading.value = true
  try {
    const res = await registrationApi.getRegistrationList({
      pageNum,
      pageSize: pageObj.pageSize,
      status: searchForm.status == -1 ? '' : searchForm.status,
      uid: searchForm.uid,
      nickname: searchForm.nickname,
      phone: searchForm.phone,
      email: searchForm.email,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime,
    })
    loading.value = false
    pageObj.page = res.data.pageNum
    pageObj.pageSize = res.data.pageSize
    pageObj.total = res.data.total
    res.data.list.forEach((item, index) => {
      item.disabled = !!item.status
    })
    data.value = res.data.list
  } catch (error) {
    loading.value = false
  }
}
const uploadPopup = ref(false)
const closeRematch = () => {
  uploadPopup.value = false
  btnLoading.value = false
}

const submitRematch = async (done) => {
  if (uploadFile.value.length) {
    uploadRef.value.submit()
  } else {
    Message.error('請選擇文件')
  }
}
const onChangeUpload = (value) => {
  uploadFile.value = value
}
const uploadRef = ref(null)
const btnLoading = ref(false)
const uploadFile = ref([])
const openUploadExcel = () => {
  uploadPopup.value = true
  uploadFile.value = []
}
const customRequest = async (option) => {
  const { onProgress, onError, onSuccess, fileItem, name } = option
  const xhr = new XMLHttpRequest()
  if (xhr.upload) {
    xhr.upload.onprogress = function (event) {
      let percent
      if (event.total > 0) {
        // 0 ~ 1
        percent = event.loaded / event.total
      }
      onProgress(percent, event)
    }
  }
  xhr.onerror = function error(e) {
    onError(e)
  }
  xhr.onload = function onload() {
    btnLoading.value = true
    if (xhr.status < 200 || xhr.status >= 300) {
      return onError(xhr.responseText)
    }
    let response = JSON.parse(xhr.response)
    if (response.code == 0) {
      // 成功
      init(1)
      btnLoading.value = false
      closeRematch()
      Message.success(response.data.message || '操作成功')
    } else {
      // 失敗
      if (response.code === 1002 || response.code === 1004) {
        Message.error(response.message || response.msg)
        router.push({ name: 'login' })
      } else {
        Message.error(response.message || response.msg)
      }
      btnLoading.value = false
    }
    onSuccess(xhr.response)
  }

  const formFileData = new FormData()
  formFileData.append(name || 'file', fileItem.file)
  const baseUrl = import.meta.env.VITE_APP_BASE_URL
  xhr.open('post', baseUrl + 'api/v1/admin/registration/csv-import-approval', true)
  xhr.send(formFileData)
  return {
    abort() {
      xhr.abort()
    },
  }
}
const registrationExcel = async () => {
  loading.value = true
  try {
    const data = await registrationApi.registrationExport({
      pageNum: pageObj.page,
      pageSize: pageObj.pageSize,
      status: searchForm.status == -1 ? '' : searchForm.status,
      uid: searchForm.uid,
      nickname: searchForm.nickname,
      phone: searchForm.phone,
      email: searchForm.email,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime,
    })
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'exported_data.csv'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
    loading.value = false
  } catch (error) {
    loading.value = false
  }
}
init()
function exportToExcel(data, fileName = 'export.xlsx') {
  // // 示例數據轉換 - 根據實際需求調整
  // const header = Object.keys(data[0]).join('\t') + '\n'
  // const rows = data.map((obj) => Object.values(obj).join('\t')).join('\n')

  // // 添加UTF-8 BOM頭

  // 使用正確的MIME類型
  const blob = new Blob([data], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8',
  })

  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = fileName
  link.click()
  URL.revokeObjectURL(link.href)
}
const crudContentRef = ref()
onMounted(async () => {
  await nextTick(() => {
    window.addEventListener('resize', settingFixedPage, false)
    settingFixedPage()
  })
})
const settingFixedPage = () => {
  const workAreaHeight = document.querySelector('.work-area').offsetHeight
  let tableHeight = workAreaHeight - 24 - 32 - 68 - 24
  if (crudContentRef.value) {
    crudContentRef.value.style.height = tableHeight + 'px'
  }
}
const dateFormat = computed(() => {
  return (val) => {
    if (!val) return '-'
    return tool.dateFormat(val)
  }
})
</script>
